/*
 *
 *  ------------------------------------------------------------------
 *  Copyright © 2017 Hangzhou DtDream Technology Co.,Lt d. All rights reserved.
 *  ------------------------------------------------------------------
 *        Product:  EMR
 *    Module Name: NEZHA
 *   Date Created: 17-10-23 下午4:22
 *    Description:
 *  ------------------------------------------------------------------
 *  Modification History
 *  DATE            Name           Description
 *  ------------------------------------------------------------------
 *  2017-10-23      NEZHA EMR
 *  ------------------------------------------------------------------
 * /
 */

package org.xukai.remoting.sdk.web.api.serde;

import com.dtdream.emr.common.NeZhaResponse;
import com.dtdream.emr.common.codec.JacksonCodec;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;

import java.io.IOException;

/**
 * Created by moriarty on 17-2-23.
 */
public abstract class HttpSerDe<T> {

    private Class<T> parameterClass;

    public HttpSerDe(Class<T> parameterClass) {
        this.parameterClass = parameterClass;
    }

    public abstract RequestBody serialize() throws IOException;

    @SuppressWarnings("unchecked")
    public T deserialize(ResponseBody body) throws IOException {
        NeZhaResponse<?> response = JacksonCodec.deserialize(body.charStream(), NeZhaResponse.class, parameterClass);
        assertNeZhaResponseNotNull(response);
        return (T) response.getBody();
    }

    protected void assertNeZhaResponseNotNull(NeZhaResponse<?> response) throws IOException {
        if (response == null) {
            throw new IOException("NeZhaResponse is null");
        }
    }
}
